package com.datawin.taotaocheche.ui.actviity.login;

import android.Manifest;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.jakewharton.rxbinding.view.RxView;
import com.datawin.taotaocheche.R;
import com.datawin.taotaocheche.base.BaseActivity;
import com.datawin.taotaocheche.comm.Constants;
import com.datawin.taotaocheche.comm.MyApplication;
import com.datawin.taotaocheche.event.NetErrorEvent;
import com.datawin.taotaocheche.ui.actviity.login.biz.LoginBiz;
import com.datawin.taotaocheche.ui.actviity.login.component.DaggerLoginComponent;
import com.datawin.taotaocheche.ui.actviity.login.contract.LoginContract;
import com.datawin.taotaocheche.ui.actviity.login.module.LoginModule;
import com.datawin.taotaocheche.ui.actviity.login.presenter.LoginPresenter;
import com.datawin.taotaocheche.util.CommonViewUtil;
import com.datawin.taotaocheche.util.LogUtils;
import com.datawin.taotaocheche.util.PermissionUtils;
import com.datawin.taotaocheche.util.PreferencesUtils;
import com.datawin.taotaocheche.util.TimerUtil;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.Bind;
import cn.jpush.android.api.JPushInterface;
import rx.functions.Action1;

public class LoginAct extends BaseActivity implements LoginContract.View {


    @Inject
    LoginPresenter loginPresenter;
    @Inject
    LoginBiz loginBiz;
    @Bind(R.id.login_view)
    View loginView;
    @Bind(R.id.register_view)
    View registerView;
    @Bind(R.id.register_layout)
    RelativeLayout registerLayout;
    @Bind(R.id.login_layout)
    RelativeLayout loginLayout;
    @Bind(R.id.login_phone_edit)
    EditText loginPhone;
    @Bind(R.id.login_pwd_edit)
    EditText loginPwd;
    @Bind(R.id.login_pwd_type)
    ImageView loginPwdType;
    @Bind(R.id.login_rember_pwd)
    TextView remberPwd;
    @Bind(R.id.login_forget_pwd)
    TextView forgetPwd;
    @Bind(R.id.login_info_layout)
    LinearLayout loginInfoLayout;
    @Bind(R.id.register_phone_edit)
    EditText registerPhone;
    @Bind(R.id.register_code_edit)
    EditText registerCode;
    @Bind(R.id.register_get_code)
    TextView getCode;
    @Bind(R.id.register_pwd_edit)
    EditText registerPwd;
    @Bind(R.id.register_pwd_type)
    ImageView registerPwdType;
    @Bind(R.id.register_info_layout)
    LinearLayout registerInfoLayout;
    @Bind(R.id.login_sumint)
    TextView loginSumint;
    @Bind(R.id.rechagre_submit)
    TextView rechagreSubmit;

    private boolean savePassword = false;
    private boolean isShowLogin = true;
    private boolean isShowRegister = true;
    private String alias;
    private TimerUtil timerUtil;

    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    //申请权限
    private final String[] PERMISSIONS = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
    };


    // 打开相机定位请求Code，多个权限请求Code
    private final int REQUEST_CODE_PERMISSIONS = 2;

    @Override
    protected void setRoot() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_login);

    }


    @Override
    protected void setup() {
        DaggerLoginComponent.builder().loginModule(new LoginModule(this)).build().inject(this);
        loginPresenter.setBiz(loginBiz);
    }

    @Override
    public void onNetErrorEvent(NetErrorEvent event) {
        super.onNetErrorEvent(event);
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
            Constants.registerActivity.add(this);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            initLocation();
            startLocation();
        } else {
            requestMorePermissions();
        }
        timerUtil = new TimerUtil(59000, 1000, getCode);
        updateUi();
        RxView.clicks(registerLayout)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        loginPresenter.showLoginOrRegister(false);
                    }
                });
        RxView.clicks(loginLayout)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        loginPresenter.showLoginOrRegister(true);
                    }
                });
        RxView.clicks(getCode)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        loginPresenter.getCode(registerPhone.getText().toString());
                    }
                });
        RxView.clicks(forgetPwd)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        loginPresenter.toForget();
                    }
                });
        RxView.clicks(loginPwdType)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        loginPresenter.showPwd(0, isShowLogin);
                    }
                });
        RxView.clicks(registerPwdType)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        LogUtils.d("------>");
                        loginPresenter.showPwd(1, isShowRegister);
                    }
                });
        RxView.clicks(loginSumint)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        loginPresenter.login(loginPhone.getText().toString().trim(), loginPwd.getText().toString().trim(), alias, savePassword);
                    }
                });
        RxView.clicks(rechagreSubmit)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        loginPresenter.register(registerPhone.getText().toString(), registerPwd.getText().toString(), registerCode.getText().toString(), alias);
                    }
                });
        RxView.clicks(remberPwd)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (savePassword) {
                            savePassword = false;
                            CommonViewUtil.setDarw(remberPwd, LoginAct.this, R.mipmap.login_select_false, -1,
                                    -1, -1);
                        } else {
                            savePassword = true;
                            CommonViewUtil.setDarw(remberPwd, LoginAct.this, R.mipmap.login_select_true, -1,
                                    -1, -1);
                        }
                    }
                });

    }


    public void updateUi() {
        if (MyApplication.userInfo != null) {
            loginPhone.setText(MyApplication.userInfo.getMobile());
            if (MyApplication.userInfo.getSave() != null && MyApplication.userInfo.getSave()) {
                loginPwd.setText(MyApplication.userInfo.getPassword());
                savePassword = true;
                CommonViewUtil.setDarw(remberPwd, this, R.mipmap.login_select_true, -1,
                        -1, -1);
            } else {
                CommonViewUtil.setDarw(remberPwd, this, R.mipmap.login_select_false, -1,
                        -1, -1);
            }
        }
        alias = PreferencesUtils.getStringPreferences("registrationId",
                "registrationId", null);
        if (alias == null || alias.equals("")) {
            alias = JPushInterface.getRegistrationID(LoginAct.this);
            PreferencesUtils.setStringPreferences("registrationId",
                    "registrationId",
                    alias);
            if (MyApplication.userInfo != null) {
                MyApplication.userInfo.setAlias(alias);
            }
        }
    }


    @Override
    public void showLayout(boolean ishow) {
        if (ishow) {
            loginView.setVisibility(View.VISIBLE);
            registerView.setVisibility(View.GONE);
            loginInfoLayout.setVisibility(View.VISIBLE);
            registerInfoLayout.setVisibility(View.GONE);
            loginSumint.setVisibility(View.VISIBLE);
            rechagreSubmit.setVisibility(View.GONE);
        } else {
            registerView.setVisibility(View.VISIBLE);
            loginView.setVisibility(View.GONE);
            registerInfoLayout.setVisibility(View.VISIBLE);
            loginInfoLayout.setVisibility(View.GONE);
            rechagreSubmit.setVisibility(View.VISIBLE);
            loginSumint.setVisibility(View.GONE);
        }
    }

    @Override
    public void countDown() {
        timerUtil.start();
    }

    @Override
    public void showPwdType(int type, boolean isshow) {
        if (type == 0) {
            if (isshow) {
                LogUtils.d("********>");
                loginPwdType.setImageResource(R.mipmap.eye_true);
                loginPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                isShowLogin = false;
            } else {
                LogUtils.d("++++++++>");
                loginPwd.setInputType(InputType.TYPE_CLASS_TEXT
                        | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                loginPwdType.setImageResource(R.mipmap.eye_defult);
                isShowLogin = true;
            }
        } else if (type == 1) {
            if (isshow) {
                registerPwdType.setImageResource(R.mipmap.eye_true);
                registerPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                isShowRegister = false;
            } else {
                registerPwdType.setImageResource(R.mipmap.eye_defult);
                registerPwd.setInputType(InputType.TYPE_CLASS_TEXT
                        | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                isShowRegister = true;
            }
        }

    }

//    @Override
//    public void clearInput() {
//        loginPhone.setText("");
//        loginPwd.setText("");
//        registerPhone.setText("");
//        registerCode.setText("");
//        registerPwd.setText("");
//    }

    @Override
    protected void onDestroy() {
        loginBiz.onDestory();
        timerUtil.onFinish();
        stopLocation();
        super.onDestroy();
    }


    /***
     * Stop location service
     */
    @Override
    protected void onStop() {
        stopLocation();
        super.onStop();
    }


    // 自定义申请多个权限
    private void requestMorePermissions() {
        PermissionUtils.checkMorePermissions(LoginAct.this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
            @Override
            public void onHasPermission() {
                initLocation();
                startLocation();
            }

            @Override
            public void onUserHasAlreadyTurnedDown(String... permission) {
//                showExplainDialog(permission, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        PermissionUtils.requestMorePermissions(LoginAct.this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
//                    }
//                });
            }

            @Override
            public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                PermissionUtils.requestMorePermissions(LoginAct.this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
            }
        });
    }


    /**
     * 解释权限的dialog
     */
    private void showExplainDialog(String[] permission, DialogInterface.OnClickListener onClickListener) {
        new AlertDialog.Builder(LoginAct.this)
                .setTitle("申请权限")
                .setMessage("我们需要" + Arrays.toString(permission) + "权限")
                .setPositiveButton("确定", onClickListener)
                .show();
    }

    /**
     * 显示前往应用设置Dialog
     */
    private void showToAppSettingDialog() {
        new AlertDialog.Builder(LoginAct.this)
                .setTitle("需要权限")
                .setMessage("我们需要相关权限，才能实现功能，点击前往，将转到应用的设置界面，请开启应用的相关权限。")
                .setPositiveButton("前往", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PermissionUtils.toAppSetting(LoginAct.this);
                    }
                })
                .setNegativeButton("取消", null).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {

            case REQUEST_CODE_PERMISSIONS:
                PermissionUtils.onRequestMorePermissionsResult(LoginAct.this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
                    @Override
                    public void onHasPermission() {
                        initLocation();
                        startLocation();
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDown(String... permission) {
                        Toast.makeText(LoginAct.this,"我们需要获取拍照等权限",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
//                        Toast.makeText(LoginAct.this, "我们需要获取拍照等权限", Toast.LENGTH_SHORT).show();
//                        showToAppSettingDialog();
                    }
                });
        }
    }

    /**
     * 初始化定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(LoginAct.this);
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }


    /**
     * 默认的定位参数
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
//        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }

    /**
     * 开始定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void startLocation() {
        //根据控件的选择，重新设置定位参数
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    /**
     * 停止定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void stopLocation() {
        // 停止定位
        if(locationClient!=null){
            locationClient.stopLocation();
        }
    }

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {
                Constants.location = location;

            }

        }
    };


}
